<template>
  <!-- 摄像头列表组件 -->
  <div class="allcameramain">
    <!-- 摄像头列表 -->
    <div class="cameralistmain">
      <div class="camera-title">摄像头列表</div>
      <div v-if="cameraList[0]" class="camera-zlist">
        <div v-for="(item, index) in cameraList" cameraList :key="index" class="camera-item" :class="{
        beselect: cameraId === item.camera.cameraId,
      }" @click="getcamermes(item.camera.cameraId, item.camera.startUp, item.camera.cameraName)">
          <i class="el-icon-video-camera"></i>
          {{ item.camera.cameraName }}
        </div>
      </div>
      <!-- 判断有没有摄像头数据 -->
      <div v-if="!cameraList[0]">
        <div class="camera-item btn">暂无摄像头</div>
      </div>
    </div>
    <!-- 摄像头控制按钮 -->
    <!-- <span>{{ btnFlag?'显示':'隐藏' }}</span> -->
    <div v-if="cameraInfoList &&
        cameraInfoList.controlFlag && btnFlag
        " class="cameracontrol">
      <div class="controne">
        <div class="contro-m z-top" @click="startcontrol(0)">
          <i class="el-icon-caret-top"></i>
        </div>
        <div class="contro-m z-left" @click="startcontrol(2)">
          <i class="el-icon-caret-left"></i>
        </div>
        <div class="contro-m z-right" @click="startcontrol(3)">
          <i class="el-icon-caret-right"></i>
        </div>
        <div class="contro-m z-bottom" @click="startcontrol(1)">
          <i class="el-icon-caret-bottom"></i>
        </div>
        <div class="contro-m z-mirror" @click="mirrorcontrol()">
          <i class="el-icon-refresh-right"></i>
        </div>
      </div>
      <div class="controtwo">
        <div class="contro-left" @click="startcontrol(10)">
          焦距
          <i class="el-icon-plus"></i>
        </div>
        <div class="contro-right" @click="startcontrol(11)">
          焦距
          <i class="el-icon-minus"></i>
        </div>
      </div>
      <div class="controthree">
        <div class="greenbut" @click="startcontrol(8)">
          <i class="el-icon-zoom-in"></i> 放大
        </div>
        <div class="greenbut" @click="startcontrol(9)">
          <i class="el-icon-zoom-out"></i>缩小
        </div>
      </div>
    </div>
    <div v-else class="cameracontrol1">
      <!-- <div class="uncontrolsty-line">此设备不可控</div> -->
      <div class="controne">
        <div class="contro-m z-top">
          <i class="el-icon-caret-top"></i>
        </div>
        <div class="contro-m z-left">
          <i class="el-icon-caret-left"></i>
        </div>
        <div class="contro-m z-right">
          <i class="el-icon-caret-right"></i>
        </div>
        <div class="contro-m z-bottom">
          <i class="el-icon-caret-bottom"></i>
        </div>
        <div class="contro-m z-mirror">
          <i class="el-icon-refresh-right"></i>
        </div>
      </div>
      <div class="controtwo">
        <div class="contro-left">
          焦距
          <i class="el-icon-plus"></i>
        </div>
        <div class="contro-right">
          焦距
          <i class="el-icon-minus"></i>
        </div>
      </div>
      <div class="controthree">
        <div class="greenbut">
          <i class="el-icon-zoom-in"></i> 放大
        </div>
        <div class="greenbut">
          <i class="el-icon-zoom-out"></i>缩小
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import nowpagereq from "@/api/video-surveillance.js";
import Axios from "axios";
import { mapGetters } from 'vuex'
import { debounce } from '@/utils/fmtTime.js';
import WebSocketClient from '@/utils/cameraWebSocket.js'
import { formatTime } from '@/utils/fmtTime.js';
export default {
  props: {
    cameralistparam: {
      type: Object,
      default: () => { }
    },
    isShowBtn: {
      type: Boolean,
      default: () => {
        return true
      }
    },
  },
  data() {
    return {
      btnFlag: false,
      cameraTimer: null,
      // 当前摄像头id
      cameraId: "",
      // 当前选中摄像头的详细信息
      cameraInfoList: {},
      // 摄像头列表
      cameraList: [],
      // 网页播放地址
      cameraurl: "",
      startUp: "",
      addressIp: '',
      openSourceMark: "",
      timer: null, // 定时器
      timer1: null, // 定时器1
      wsClient: null,
      pingTimer: '',
      isWatchVideoTraffic: false  //是否需要监听流量
    };
  },

  computed: {
    ...mapGetters([
      'codeList'
    ])
  },
  watch: {
    cameralistparam(newval) {
      this.getcameralist();
    }
  },
  async mounted() {
    this.btnFlag = this.codeList.indexOf('control') !== -1;
    this.getAddressIp()
  },
  beforeDestroy() {
    clearInterval(this.cameraTimer)
    // 离开界面销毁预热
    this.closePreheat();
    clearTimeout(this.timer);
    clearTimeout(this.timer1);
    this.wsClientClose();
    this.timer = null;
    this.timer1 = null;
    this.cameraId = "";
    this.openSourceMark = "";
  },
  methods: {
    // 获取摄像头列表
    getcameralist() {
      this.$emit("nowcameraurl", "transCamera");
      let params = this.cameralistparam;
      params.organizationNo = sessionStorage.organizationNo;
      this.cameraList = [];
      if (!params.facilityNo) {
        this.timer1 = null;
        clearTimeout(this.timer1);
        return;
      }
      nowpagereq.gethbcameraList(params.facilityNo).then(res => {
        if (res.code === 1) {
          if (res.data.length >= 1) {
            this.cameraList = res.data;
            console.log("列表有摄像头");
            ;
            this.getcamermes(
              res.data[0]["camera"]["cameraId"],
              res.data[0]["camera"]["startUp"],
              res.data[0]["camera"]["cameraName"]
            );
          } else {
            this.getcamermes(-1, "false");
          }
        } else {
          this.getcamermes(-1, "false");
          this.$emit("nowcameraurl", "notCameraList");
          console.log("列表请求摄像头失败");
        }
      });
    },
    wsClientClose() {
      if (this.wsClient) {
        this.wsClient.close();
        this.wsClient = null
      }
    },
    // 获取某个摄像头详细信息
    getcamermes: debounce(async function (id, newStartUp, cameraName) {
      //关闭ws
      this.wsClientClose();
      this.timer1 = null;
      clearTimeout(this.timer1);
      this.$emit("nowcameraurl", "transCamera");
      if (this.startUp === "true") {
        this.closePreheat(this.cameraId);
        console.log("销毁预热");
      }
      if (id === -1) {
        this.$emit("nowcameraurl", "notCameraList");
        console.log("列表无摄像头");
        this.cameraId = id;
        this.cameraName = cameraName
        this.startUp = newStartUp;
        return;
      }
      // if (this.cameraId && this.openSourceMark) {
      //   this.closePreheat(this.cameraId);
      // }
      this.cameraId = id;
      this.cameraName = cameraName
      this.startUp = newStartUp;
      // 注意：startUp是字符串，不是Boolean
      if (newStartUp === "true") {
        this.openSourceMark = new Date().getTime();
        await Axios({
          method: "post",
          url:
            this.$cloudBaseurl + "iotApplication/solarEnergyCamera/openPower",
          data: { cameraId: id, openSourceMark: this.openSourceMark }
        }).then(
          res => {
            console.log(res);
            if (res.data.data.whetherPreheat) {
              // 子向父传值
              this.$emit("getUploadTime", res.data.data.openTime, this.startUp);
              console.log("预热加载");
              this.timer1 = setTimeout(() => {
                this.getSame(id);
              }, res.data.data.openTime * 60000);
            } else {
              this.getSame(id);
            }
          },
          err => {
            console.log(err);
          }
        );
      } else {
        this.openSourceMark = "";
        this.getSame(id);
      }
    }, 1000),
    getSame(id) {
      this.cameraId = id
      if (this.isWatchVideoTraffic) {
        this.initWebSocket(id)
      } else {
        this.getcamermeInfo(id);
      }
    },
    // 封装获取摄像详细信息流量相关
    async getcamermeInfo(id) {
      this.cameraTimer = setInterval(async () => {
        if (id !== -1) {
          this.$emit("nowcameraurl", "downFlow");
          clearInterval(this.cameraTimer)
        }
      }, 60 * 1000 * 10)
      nowpagereq.getcameramessage(id).then(res => {
        if (res.code === 1) {
          let data = res.data;
          this.cameraInfoList = data.camera;
          console.log("取得摄像头数据进行拼接");
          this.setcameraurl();
        }
      });
    },
    async getAddressIp() {
      await Axios({
        method: "get",
        url: "https://qifu-api.baidubce.com/ip/local/geo/v1/district"
      }).then(res => {
        let data = res.data;
        this.addressIp = data.ip
      }).catch(err => {
        // fetch('https://gifu-api.baidubce.com/ip/local/geo/v1/district')
        //   .then(response => response.json())
        //   .then(data => {
        //     this.addressIp = data.ip
        //   })
        //   .catch(error => console.error('Error:', error));
      })
    },
    //发送type:100=>是否播放 200:开始计时
    sendWebSocket(type) {
      let content = {
        operator: sessionStorage.username,
        cameraId: this.cameraId,
        cameraName: this.cameraName,
        deviceType: 'WEB',
        sourceSystem: sessionStorage.organizationName,
        ipAddress: this.addressIp
      }
      this.wsClient.send(JSON.stringify({
        type,
        content
      }));
    },
    initWebSocket() {
      let username = sessionStorage.username;
      let that = this;
      let cameraId = this.cameraId
      this.wsClient = new WebSocketClient(this.$webSocketCaramsUrl + username);
      this.wsClient.onOpen = () => {
        let pingInterval = 15000; // 设定定时器发送心跳包
        that.sendWebSocket(100)
        that.pingTimer = setInterval(function () {
          that.wsClient && that.wsClient.send('ping');
        }, pingInterval);
      };
      this.wsClient.onMessage = (event) => {
        //如果是pond不需要解析
        console.log(event.data)
        if (event.data == 'pong') {
          console.log('心跳:', new Date())
        } else {
          let { code, msg, data } = JSON.parse(event.data)
          if (code == 1) {
            this.getcamermeInfo(cameraId);
          } else if (code == 0) {
            if (data == 'Popup') {
              //弹窗提示
              that.$alert('流量不足，请联系运营充值！', '流量提醒', {
                confirmButtonText: '确定',
                callback: action => {
                  that.$message({
                    type: 'info',
                    message: '请联系运营充值！'
                  });
                }
              });
            } else if (data == 'ForbidPlayback') {
              //禁止播放
              this.$message.warning(msg);
            } else {
              this.$message.warning(msg);
            }
            this.$emit("nowcameraurl", "downFlow");
            this.wsClientClose();
          } else {
            this.$emit("nowcameraurl", "notCameraData");
            this.wsClientClose();
          }
        }
      };
      this.wsClient.onClose = () => {
        console.log(`关闭ws:摄像头${cameraId}`);
      };
      this.wsClient.onError = (error) => {
        console.error('失败ws:', `摄像头${cameraId}`, error);
      };
    },
    sendErrorInfo(e) {
      //摄像头异常
      let errorInfo = {
        cameraId: this.cameraId,
        cameraName: this.cameraName,
        errorCode: e.retcode,
        errorMsg: e.msg,
        errorTime: formatTime(new Date(), 'yyyy-MM-dd HH:mm:ss')
      }
      this.addCamerError(errorInfo)
    },
    async addCamerError(errorInfo = {}) {
      await Axios({
        method: "post",
        // url: "http://192.168.20.117:8080/iotApplication/cameraAbnormalLog/add",
        url: this.$cloudBaseurl + "/iotApplication/cameraAbnormalLog/add",
        data: { ...errorInfo }
      }).then(
        res => {
          console.log(res)
          this.wsClient.close();
        },
        err => {
          console.log(err)
          this.wsClient.close();
        }
      );
    },
    // 封装预热销毁函数
    async closePreheat(id) {
      await Axios({
        method: "post",
        url: this.$cloudBaseurl + "iotApplication/solarEnergyCamera/closePower",
        data: { cameraId: id, openSourceMark: this.openSourceMark }
      }).then(
        res => {
          console.log(res);
          console.log("预热销毁成功");
        },
        err => {
          console.log(err);
        }
      );
    },
    async getcams(id) {
      let zhurl =
        this.$cloudBaseurl +
        `iotApplication/cameraOperation/judgeFlow?cameraId=${id}`;
      const { data: res } = await Axios({
        method: "get",
        url: zhurl
      });
      // console.log(res)
      let data = res.data;
      if (res.code === 1) {
        // console.log(data.basis)
        if (data.flowUse) {
          this.$message.success(
            "总流量" + data.flowTotal + "已使用流量" + data.flowUse
          );
        }
        return data.basis;
      } else {
        this.$message.warning(res.msg || "未知错误！！！");
        return false;
      }
    },
    // 拼接摄像头地址
    setcameraurl() {
      // 判断有无摄像头
      if (this.cameraInfoList) {
        if (this.cameraInfoList.cameraInfo.status === 1) {
          // alert(this.cameraInfoList['deviceSerial'])
          this.cameraurl = "";
          // console.log(this.cameraInfoList)
          if (this.cameraInfoList) {
            this.cameraurl = `https://open.ys7.com/ezopen/h5/iframe?url=ezopen://open.ys7.com/${this.cameraInfoList["deviceSerial"]}/${this.cameraInfoList["channelNo"]}.hd.live&autoplay=1&accessToken=${this.cameraInfoList["accessToken"]}`;
          }
          this.$emit("nowcameraurl", this.cameraurl, { id: 'video-container', accessToken: this.cameraInfoList["accessToken"], url: `ezopen://open.ys7.com/${this.cameraInfoList["deviceSerial"]}/${this.cameraInfoList["channelNo"]}.hd.live` });
          this.timer = setTimeout(() => {
            this.$emit("nowcameraurl", "timeout");
          }, 1000 * 60 * 20);
        } else {
          this.$message.warning("摄像头不在线！请稍后重试");
          this.$emit("nowcameraurl", "notCameraData");
          return;
        }
      } else {
        // 无 传空
        // this.cameraurl = null
        this.$emit("nowcameraurl", "notCameraList");
      }
    },
    // 开始控制
    async startcontrol(i) {
      this.timer = setTimeout(() => {
        this.$emit("nowcameraurl", "timeout");
      }, 1000 * 60 * 20);
      let params = {
        cameraId: this.cameraId,
        direction: i,
        speed: 1
      };
      await nowpagereq.controlcamera(params).then(res => {
        if (res.code != 200) this.$message.error(res.msg);
      });
      setTimeout(() => {
        this.stopcontrol();
      }, 1000);
    },
    // 镜像翻转
    async mirrorcontrol() {
      this.timer = setTimeout(() => {
        this.$emit("nowcameraurl", "timeout");
      }, 1000 * 60 * 20);
      let params = {
        cameraId: this.cameraId,
        direction: 2,
        speed: 1
      };
      await nowpagereq.mirrorcamera(params);
      setTimeout(() => {
        this.stopcontrol();
      }, 1000);
    },
    // 停止控制
    stopcontrol() {
      let params = {
        cameraId: this.cameraId
      };
      nowpagereq.stopcamera(params).then(res => {
        // console.log(res)
      });
    }
  }
};
</script>

<style lang="scss" scoped>
$height: 40px;

.uncontrolsty {
  width: 100%;
  height: calc(70% - 10px);
  // padding: 0 15px;
  margin-top: 10px;
  display: flex;
  justify-content: center;
  align-items: center;

  .uncontrolsty-line {
    color: #ccc;
    font-size: 30px;
    width: 30px;
    line-height: 50px;
  }
}

.allcameramain {
  height: 100%;
  width: 100%;

  .one {
    width: 100%;
    line-height: 40px;
    margin-bottom: 15px;
    text-align: center;
    font-size: 18px;
    border-radius: 5px;
    border: 1px solid #fff;
  }
}

.cameralistmain {
  width: 100%;
  height: 290px;
  text-align: center;
  overflow: auto;

  .camera-title {
    line-height: 40px;
    font-size: 18px;
    color: #335068;
  }

  .camera-item {
    height: 50px;
    line-height: 50px;
    background-color: #4381b5;
    margin-bottom: 10px;
    border-radius: 6px;
    color: #ffffff;
    cursor: pointer;

    &:hover {
      background-color: #335068;
    }
  }

  .beselect {
    background-image: linear-gradient(to right, #335068, #4381b5, #335068);
  }
}

.cameracontrol {
  width: 100%;
  height: calc(100% - 290px);
  margin-top: 10px;

  .controne {
    width: 100%;
    height: calc(100% - 160px);
    background-image: url("~@/assets/camera/ctrlBg.png");
    background-repeat: no-repeat;
    background-size: 90%;
    background-position: center;
    position: relative;

    .contro-m {
      position: relative;
      width: 25%;
      height: 25%;
      text-align: center;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 40px;
      cursor: pointer;
    }

    .contro-m:hover {
      font-size: 48px;
    }

    .z-top {
      top: 10%;
      left: 37%;
    }

    .z-left {
      top: 12%;
      left: 11%;
    }

    .z-right {
      top: -13%;
      left: 63%;
    }

    .z-bottom {
      top: -10%;
      left: 37%;
    }

    .z-mirror {
      top: -63%;
      left: 37%;
    }
  }

  .controtwo {
    width: 100%;
    height: 15%;
    display: flex;
    justify-content: space-around;

    .contro-left {
      width: 48%;
      height: 100%;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      // border: #46c357 1px solid;
      background-image: url("~@/assets/camera/transformLeft.png");
      background-repeat: no-repeat;
      background-size: 70%;
      background-position: center;
      padding-right: 11%;
      cursor: pointer;
      font-size: 18px;
      text-align: center;
    }

    .contro-left:hover {
      font-size: 20px;
    }

    .contro-right {
      width: 48%;
      height: 100%;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      // border: #46c357 1px solid;
      background-image: url("~@/assets/camera/transformRight.png");
      background-repeat: no-repeat;
      background-size: 70%;
      background-position: center;
      padding-left: 11%;
      cursor: pointer;
      font-size: 18px;
    }

    .contro-right:hover {
      font-size: 20px;
    }
  }

  .controthree {
    width: 100%;
    height: 80px;
    display: flex;
    justify-content: space-around;
    align-items: center;

    .greenbut {
      width: 28%;
      height: 60%;
      background-color: rgb(0, 127, 185);
      border-radius: 5px;
      text-align: center;
      display: flex;
      justify-content: center;
      align-items: center;
      font-weight: 600;
      font-size: 22px;
      cursor: pointer;
    }

    .greenbut:hover {
      font-size: 24px;
    }
  }
}

.cameracontrol1 {
  width: 100%;
  height: calc(100% - 290px);
  margin-top: 10px;
  opacity: 0.5;

  .controne {
    width: 100%;
    height: 60%;
    background-image: url("~@/assets/camera/ctrlBg.png");
    background-repeat: no-repeat;
    background-size: 100% 100%;
    background-position: center;
    position: relative;

    .contro-m {
      position: relative;
      width: 25%;
      height: 25%;
      text-align: center;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 40px;
      cursor: pointer;
    }

    .z-top {
      top: 10%;
      left: 37%;
    }

    .z-left {
      top: 12%;
      left: 11%;
    }

    .z-right {
      top: -13%;
      left: 63%;
    }

    .z-bottom {
      top: -10%;
      left: 37%;
    }

    .z-mirror {
      top: -63%;
      left: 37%;
    }
  }

  .controtwo {
    width: 100%;
    height: 75px;
    display: flex;
    justify-content: space-around;

    .contro-left {
      width: 48%;
      height: 100%;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      background-image: url("~@/assets/camera/transformLeft.png");
      background-repeat: no-repeat;
      background-size: 70%;
      background-position: center;
      padding-right: 11%;
      // mix-blend-mode: soft-light;
      cursor: pointer;
      font-size: 18px;
    }

    .contro-right {
      width: 48%;
      height: 100%;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      // border: #46c357 1px solid;
      background-image: url("~@/assets/camera/transformRight.png");
      background-repeat: no-repeat;
      background-size: 70%;
      background-position: center;
      padding-left: 11%;
      // mix-blend-mode: soft-light;
      cursor: pointer;
      font-size: 18px;
    }
  }

  .controthree {
    width: 100%;
    height: 17%;
    display: flex;
    justify-content: space-around;
    align-items: center;

    .greenbut {
      width: 40%;
      height: 60%;
      background-color: rgb(0, 127, 185);
      border-radius: 5px;
      text-align: center;
      display: flex;
      justify-content: center;
      align-items: center;
      font-weight: 600;
      font-size: 22px;
      cursor: pointer;
    }
  }
}

.zlistbtn {
  display: flex;
  justify-content: center;
  align-items: center;

  .btn {
    border: none !important;
    height: 100%;
  }
}
</style>
